﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Markup;
using System.ComponentModel;
using System.Reflection;
using UIT.Controls;

namespace UIT.Markup
{
#if !SILVERLIGHT
    [MarkupExtensionReturnType(typeof(IControl))]
#endif
    public class Control : MarkupExtension, INotifyPropertyChanged, IDisposable
    {
        public Control()
        {
        }

        public Control(string name)
        {
            Name = name;
        }

        public override object ProvideValue(IServiceProvider serviceProvider)
        {
            if (serviceProvider == null)
                return this;
            IProvideValueTarget provider = (IProvideValueTarget)serviceProvider.GetService(typeof(IProvideValueTarget));
            IControl controlToSearchFrom = provider.TargetObject as IControl;
            IControlFinder finder = Context.Current.Application.ControlFinder;
            return finder.Find(Name, controlToSearchFrom);
        }

        private void OnPropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }

        public event PropertyChangedEventHandler PropertyChanged;

        public void Dispose()
        {

        }

        private string name;

        public string Name
        {
            get { return name; }
            set
            {
                name = value;
                OnPropertyChanged("Name");
            }
        }
    }
}
